<?php

namespace app\commands;

use app\models\Sms;
use app\models\user\User;
use app\models\user\UserAccount;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\db\Exception;

class FlushController extends Controller
{
    // php yii flush/index
    // php yii flush/index 1
    public function actionIndex($delete_user = 1)
    {
        $delete_user = intval($delete_user);

        $this->clear('sms');

        $this->clear('order');
        $this->clear('order_item');
        $this->clear('order_active');
        $this->clear('order_logistics');
        // $this->clear('order_store');
        // $this->clear('order_store_extract');

        $this->clear('pay');
        $this->clear('pay_for');

        // 充值列表
        $this->clear('transfer');

        // 分红
        $this->clear('month_profit');

        if ($delete_user) {
            echo 'Clear All ...', "\n";

            $this->clear('user');
            $this->clear('user_account');
            $this->clear('user_address');

            $my_id = 11194;
            $my_pass = '222222';

            // 添加一个
            for ($i = 0 ; $i < $delete_user; $i++) {
                $model = new User();
                $model->nickname = base64_encode('测试会员');
                $model->mobile = strval(18620885097 + $i);
                $model->password = $my_pass;
                if ($i == 0) {
                    $model->id = strval($my_id);
                }
                if ($i < 10 - 1) {
                    $model->referrer_id = strval($my_id + $i + 1);
                }
                if ($model->save()) {
                    $account = new UserAccount();
                    $account->user_id = $model->id;
                    if ($i == 0) {
                        $account->balance = 8888888;
                    }
                    $account->save();
                }
            }

            // $this->clear('user_address');
            // $this->clear('user_pay_password');
        }

        $this->clear('user_bank');
        $this->clear('user_cart');
        $this->clear('user_refill');
        $this->clear('user_sign_in');
        $this->clear('user_commission');
        $this->clear('user_consume');
        $this->clear('user_cash');
        $this->clear('user_fav');

        $this->clear('admin_ops_refill');

        $this->clear('group');
        $this->clear('group_fans');

        return ExitCode::OK;
    }

    private function clear($table_name)
    {
        try {
            echo 'Clear ' . $table_name . ' ................. done!', "\n";
            Sms::getDb()->createCommand()->truncateTable($table_name)->execute();
        } catch (Exception $e) {
            echo 'error: ' . $e->getMessage(), "\n";
        }
    }
}